package com.solcoo.controller;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.solcoo.dao.CheckTimeDao;
import com.solcoo.dao.DingDanDao;
import com.solcoo.dao.TempKeHuDao;
import com.solcoo.dao.YongHuDao;
import com.solcoo.dao.ZhangHuDao;
import com.solcoo.dao.ZheKouDao;
import com.solcoo.json.EmployeeJson;
import com.solcoo.pojo.CheckTime;
import com.solcoo.pojo.DingDan;
import com.solcoo.pojo.RechargeInfo;
import com.solcoo.pojo.TempGR;
import com.solcoo.pojo.TempKeHu;
import com.solcoo.pojo.TempKeHuAndSL;
import com.solcoo.pojo.TempSH;
import com.solcoo.pojo.TempSeller;
import com.solcoo.pojo.Useromrela;
import com.solcoo.pojo.YongHu;
import com.solcoo.pojo.ZhangHu;
import com.solcoo.pojo.ZheKou;
import com.solcoo.service.RechargeService;
import com.solcoo.service.YongHuService;
import com.solcoo.dao.UseromrelaDao;
import com.solcoo.util.SendMsgUtil;

@Controller
public class YongHuController extends AbstractController{
    @Resource
    private YongHuDao yongHuDao;
    @Resource
    private TempKeHuDao tempKeHuDao;
    @Resource
    private ZhangHuDao zhangHuDao;
    @Resource
    private DingDanDao dingDanDao;
    @Resource
    private ZheKouDao zheKouDao;
	@Resource
	private CheckTimeDao checkTimeDao;
    @Resource
    private UseromrelaDao useromrelaDao;
    @Resource
    private YongHuService yongHuService;
    @Resource
    private RechargeService rechargetService;

    private static final String ip = "42.120.7.37";

    private static Logger logger = Logger.getLogger(YongHuController.class);

    public static final String separator = File.separator;

	// 生成验证码  ，发送到手机端
    @RequestMapping(value="check.do")
    public @ResponseBody JsonResult check(String shoujih) throws Exception {
    	if(shoujih==null || !shoujih.matches("[0-9]{11}")) {
    		return getFailJsonResult("手机号格式错误");
    	}
    	CheckTime checkTime = new CheckTime();
    	checkTime.setShoujih(shoujih);
    	checkTime.setLeixing("1");
    	CheckTime ct = checkTimeDao.getCheckTime(checkTime);
    	if(ct != null) {
    		Long subTime = (System.currentTimeMillis() - ct.getShijian()) / 1000;
    		if(subTime > 59) {
    			ct.setShijian(System.currentTimeMillis());
    			checkTimeDao.updateCheckTime(ct);
    		} else {
    			return getFailJsonResult("网络异常，请稍后重试");
    		}
    	} else {
    		ct = new CheckTime();
    		ct.setLeixing("1");
    		ct.setShijian(System.currentTimeMillis());
    		ct.setShoujih(shoujih);
    		checkTimeDao.addCheckTime(ct);
    	}
    	
        YongHu exsitUserCount = yongHuDao.selectUserByPhone(shoujih);
        if(exsitUserCount != null) { //如果已经存在该用户(指注册的手机号)
            return this.getFailJsonResult("该手机号已经注册");
        }
        
        // 发送验证码短信
        String yhm = (int)(Math.random()*100000) + "";
        while(yhm.length() < 5) {
            yhm = "0" + yhm;
        }
        String validateMsg = yhm+"【搜卡验证码】";
        SendMsgUtil sms = new SendMsgUtil(shoujih, validateMsg, "2");
        new Thread(sms).start();
        
        return this.getSuccessJsonResult(yhm);
    }

	// 用户注册
    @RequestMapping(value="signup.do")
    public @ResponseBody JsonResult signup(YongHu yongHu) throws Exception {
    	if(yongHu.getShoujih()==null || !yongHu.getShoujih().matches("[0-9]{11}")) {
    		return getFailJsonResult("手机号格式错误");
    	}
        YongHu exsitUserCount = yongHuDao.selectUserByPhone(yongHu.getShoujih());
        if(exsitUserCount != null) { //如果已经存在该用户(指注册的手机号)
            return this.getFailJsonResult("该手机号已经注册");
        }
        yongHu.setYonghum(fillIdWith5Length(yongHu));
        yongHu.setZhucesj(new Date());
        yongHuDao.addYongHu(yongHu);
        
        // 发送短信
        String validateMsg = "非常感谢使用【搜卡】，我们愿成为您的省钱工具，如果搜卡实在太烂，请果断吐槽。（微博：搜卡solcoo）";
        SendMsgUtil sms = new SendMsgUtil(yongHu.getShoujih(), validateMsg, "2");
        new Thread(sms).start();
        
        if("3".equals(yongHu.getLeixing())) {
        	EmployeeJson mj = new EmployeeJson();
        	mj.setEnabled("0");
        	mj.setShoujih(yongHu.getShoujih());
        	mj.setYonghum(yongHu.getYonghum());
        	return this.getSuccessJsonResult(mj);
        } else {
        	return getSuccessJsonResult(yongHu);
        }
    }

	// 将id填充为5个字符长度
    private String fillIdWith5Length(YongHu yongHu) throws Exception {
        YongHu user = null;
        String yhm = "";
        do {
            yhm = (int)(Math.random()*100000) + "";
//            while(yhm.length() < 5) {
//                yhm = "0" + yhm;
//            }
            if(yhm.length() == 5)
            	user = yongHuDao.selectUserByYonghum(yhm);
        } while(yhm.length()!=5 || user != null);
        return yhm;
    }

    // 用户登录
    @RequestMapping(value="login.do")
    public @ResponseBody JsonResult login(String yonghum, String mima, String qrcode) throws Exception {
        YongHu yongHu = yongHuDao.selectUserByPhone(yonghum);
        if(yongHu == null) {
            return this.getFailJsonResult("该用户不存在");
        }
        if(mima == null || "".equals(mima) || !mima.equals(yongHu.getMima())) {
            return this.getFailJsonResult("密码错误");
        }
        if("3".equals(yongHu.getLeixing())) {
        	EmployeeJson mj = new EmployeeJson();
        	mj.setShoujih(yongHu.getShoujih());
        	mj.setYonghum(yongHu.getYonghum());
        	mj.setNicheng(yongHu.getNicheng());
        	mj.setTouxiang(yongHu.getTouxiang());
        	Useromrela ur = useromrelaDao.getEnabledEmployee(yongHu.getYonghum());
        	if(ur != null) {
        		mj.setEnabled("1");
        		mj.setEno(ur.getEno());
        	} else {
        		mj.setEnabled("0");
        	}
        	yongHuDao.updateQrcode(yonghum, qrcode);
        	return this.getSuccessJsonResult(mj);
        } else {
        	yongHuDao.updateQrcode(yonghum, qrcode);
        	return getSuccessJsonResult(yongHu);
        }
    }

    // 用户修改信息，用户名必填，其他字段如果有值则修改
    @RequestMapping(value="update.do")
    public @ResponseBody JsonResult update(YongHu yongHu) throws Exception {
        // 昵称唯一
        if(yongHu.getNicheng()!=null && !"".equals(yongHu.getNicheng())) {
            YongHu exsitUser = yongHuDao.selectUserByNicheng(yongHu.getNicheng());
            if(exsitUser!=null && !exsitUser.getYonghum().equals(yongHu.getYonghum())) {
                return this.getFailJsonResult("该昵称已存在");
            }
        }

        // 店名唯一
        if(yongHu.getDianming()!=null && !"".equals(yongHu.getDianming())) {
            YongHu exsitUser2 = yongHuDao.selectUserByDianMing(yongHu.getDianming());
            if(exsitUser2!=null && !exsitUser2.getYonghum().equals(yongHu.getYonghum())) {
                return this.getFailJsonResult("该店名已存在");
            }
        }

        boolean b = yongHuDao.update(yongHu);
        if(b) {
            YongHu newyh = yongHuDao.selectUserByYonghum(yongHu.getYonghum());
            if("3".equals(newyh.getLeixing())) {
            	EmployeeJson mj = new EmployeeJson();
            	mj.setShoujih(newyh.getShoujih());
            	mj.setYonghum(newyh.getYonghum());
            	mj.setNicheng(newyh.getNicheng());
            	mj.setTouxiang(newyh.getTouxiang());
            	Useromrela ur = useromrelaDao.getEnabledEmployee(newyh.getYonghum());
            	if(ur != null) {
            		mj.setEnabled(ur.getEnabled());
            		mj.setEno(ur.getEno());
            	} else {
            		mj.setEnabled("0");
            	}
            	return this.getSuccessJsonResult(mj);
            } else {
            	return getSuccessJsonResult(newyh);
            }
        } else {
            logger.error("用户名为"+yongHu.getYonghum()+"的用户修改失败！");
            return this.getFailJsonResult("系统异常，请重试");
        }
    }

    // 用户修改头像，用户名必填，其他字段如果有值则修改
    @RequestMapping(value="updatePic.do")
    public @ResponseBody JsonResult updatePic(YongHu yongHu, @RequestParam(required=false) MultipartFile pic) throws Exception {
        // 头像接收
        if(pic!=null && !pic.isEmpty()) {
            String filename = ""; // 头像接收后存放的路径
            String projectPath = System.getProperty("user.dir").replace("bin", "webapps").replaceAll("\\\\", "/");
            String picPath = projectPath + "/Solcoo/static/";
            String urlPath = "http://" + ip + "/Solcoo/static/";
            String rootPath = "";
            String oldPath = "";
            YongHu yh = yongHuDao.selectUserByYonghum(yongHu.getYonghum());
            String yhtx = yh.getTouxiang();
            if(yhtx!=null && !"".equals(yhtx)) {
                oldPath = yhtx.replace(urlPath, picPath);
            }
            File file = new File(picPath);
            if (!file.exists())
                file.mkdirs();
            rootPath = picPath + new Date().getTime();
            filename = rootPath.replace(picPath, urlPath);
            File picc = new File(rootPath);
            pic.transferTo(picc);
            yongHu.setTouxiang(filename);
            boolean b = yongHuDao.update(yongHu);
            if(b) {
                if(oldPath != null && !"".equals(oldPath)) {
                    File oldfile = new File(oldPath);
                    oldfile.delete();
                }
                YongHu newyh = yongHuDao.selectUserByYonghum(yongHu.getYonghum());
                if("3".equals(newyh.getLeixing())) {
                	EmployeeJson mj = new EmployeeJson();
                	mj.setShoujih(newyh.getShoujih());
                	mj.setYonghum(newyh.getYonghum());
                	mj.setNicheng(newyh.getNicheng());
                	mj.setTouxiang(newyh.getTouxiang());
                	Useromrela ur = useromrelaDao.getEnabledEmployee(newyh.getYonghum());
                	if(ur != null) {
                		mj.setEnabled(ur.getEnabled());
                		mj.setEno(ur.getEno());
                	} else {
                		mj.setEnabled("0");
                	}
                	return this.getSuccessJsonResult(mj);
                } else {
                	return getSuccessJsonResult(newyh);
                }
            } else {
                logger.error("用户名为"+yongHu.getYonghum()+"的头像修改失败！");
                return this.getFailJsonResult("系统异常，请重试");
            }
        } else {
            logger.error("用户名为"+yongHu.getYonghum()+"的头像上传为空！");
            return this.getFailJsonResult("系统异常，请重试");
        }
    }

    // 短信找回密码
    @RequestMapping(value="forgetPasswd.do")
    public @ResponseBody JsonResult forgetPasswd(String telephone) throws Exception {
    	if(telephone==null || !telephone.matches("[0-9]{11}")) {
    		return getFailJsonResult("手机号格式错误");
    	}
//    	CheckTime checkTime = new CheckTime();
//    	checkTime.setShoujih(telephone);
//    	checkTime.setLeixing("2");
//    	CheckTime ct = checkTimeDao.getCheckTime(checkTime);
//    	if(ct != null) {
//    		Long subTime = (System.currentTimeMillis() - ct.getShijian()) / 1000 / 60;
//    		if(subTime > 10) {
//    			ct.setShijian(System.currentTimeMillis());
//    			checkTimeDao.updateCheckTime(ct);
//    		} else {
//    			return getFailJsonResult("该功能需10分钟冷却时间，请在"+ (10 - subTime) + "分钟之后重试");
//    		}
//    	} else {
//    		ct = new CheckTime();
//    		ct.setLeixing("2");
//    		ct.setShijian(System.currentTimeMillis());
//    		ct.setShoujih(telephone);
//    		checkTimeDao.addCheckTime(ct);
//    	}
    	
    	// 发送密码短信
		YongHu yh = yongHuDao.selectUserByPhone(telephone);
		if(yh == null) {
			return this.getFailJsonResult("手机号码错误，请核对确认");
		}
		String validateMsg = "您账户的密码为:" + yh.getMima() + " ";
        SendMsgUtil sms = new SendMsgUtil(telephone, validateMsg, "2");
        new Thread(sms).start();
		
        return this.getSuccessJsonResult("已发送");
    }
    
    // 修改密码
    @RequestMapping(value="updatePasswd.do")
    public @ResponseBody Map<String, Object> updatePasswd(String telephone, String oldPasswd, String newPasswd) throws Exception {
    	return yongHuService.updatePasswd(telephone, oldPasswd, newPasswd);
    }
    
    // 商户查询个人列表
    @RequestMapping(value="shQueryGrs.do")
    public @ResponseBody JsonResult shQueryGrs(int shanghuid,int youbiao) throws Exception {
        List<TempKeHu> khs = tempKeHuDao.queryList(shanghuid, youbiao);
        if(khs.size() > 0)
            youbiao = khs.get(khs.size()-1).getId();
        List<TempKeHu> khsa = tempKeHuDao.queryList(shanghuid, youbiao);
        if(khsa==null || khsa.size()<=0) {
            youbiao = -1;
        }
        TempKeHuAndSL khsl = new TempKeHuAndSL();
        khsl.setMyList(khs);
        khsl.setYoubiao(youbiao);
        int memberNum = zhangHuDao.getMemberNum(shanghuid);
        khsl.setMemberNum(memberNum);
        return getSuccessJsonResult(khsl);
    }

    // 商户查询个人信息
    @RequestMapping(value="shQueryGr.do")
    public @ResponseBody JsonResult shQueryGr(int shanghuid, int gerenid) throws Exception {
        int youbiao = 0;
        ZhangHu zh = zhangHuDao.query(shanghuid, gerenid);
        TempKeHu kh = tempKeHuDao.query(shanghuid, gerenid);
        List<DingDan> dds = dingDanDao.queryList(shanghuid, gerenid, 0);
        if(dds.size() > 0)
            youbiao = dds.get(dds.size()-1).getId();
        List<DingDan> ddsa = dingDanDao.queryList(shanghuid, gerenid, youbiao);
        if(ddsa==null || ddsa.size()<=0) {
            youbiao = -1;
        }
        TempGR tgr = new TempGR();
        tgr.setZh(zh);
        tgr.setKh(kh);
        tgr.setMyList(dds);
        tgr.setYoubiao(youbiao);
        
        // 推送相关
        Map<String, Object> param = new HashMap<String, Object>();
    	param.put("shanghuid", zh.getShanghuid());
    	param.put("gerenid", zh.getGerenid());
    	param.put("shNQCount", 0);
    	param.put("shanghuid", zh.getShanghuid());
    	zhangHuDao.updateNQCount(param);
    	dingDanDao.updateDDNQCount(param);
        
        return this.getSuccessJsonResult(tgr);
    }

    // 个人查询会员商户列表
    @RequestMapping(value="grQueryHysh.do")
    public @ResponseBody JsonResult grQueryHysh(int gerenid,int youbiao) throws Exception {
        List<TempSeller> sellers = zhangHuDao.querySellerInfoByUserId(gerenid,youbiao);
        if(sellers.size() > 0)
            youbiao = sellers.get(sellers.size()-1).getUser().getId();
        List<TempSeller> sellersa = zhangHuDao.querySellerInfoByUserId(gerenid,youbiao);
        if(sellersa==null || sellersa.size()<=0) {
            youbiao = -1;
        }
        return this.getSuccessJsonResult(sellers, youbiao);
    }

 // 个人查询商户信息
    @RequestMapping(value="grQuerySh.do")
    public @ResponseBody JsonResult grQuerySh(int shanghuid, int gerenid) throws Exception {
        String shyhm = shanghuid + "";
        while(shyhm.length() < 5) {
            shyhm = "0" + shyhm;
        }
        YongHu sh = yongHuDao.selectUserByYonghum(shyhm);
        ZhangHu zh = zhangHuDao.query(shanghuid, gerenid);
        // 获取下个级别所需要的经验值
        double jyz = -1;
        if(zh != null) {
            ZheKou zk = zheKouDao.selectNextLevelObject(shanghuid, zh.getJingyanz());
            if(zk!=null)
                jyz = zk.getJingyanz();
        }
        
        List<RechargeInfo> ris = rechargetService.selectRechargeInfo(shyhm); // 活动List
        List<ZheKou> zheKouList = zheKouDao.queryListByShid(shanghuid); // 折扣List
        
        TempSH tsh = new TempSH();
        
        tsh.setYonghu(sh);
        tsh.setZhanghu(zh);
        tsh.setJyz(jyz);
        tsh.setRechargeInfoList(ris);
        tsh.setZheKouList(zheKouList);
        
        return this.getSuccessJsonResult(tsh);
    }

    // 个人查询所有商户列表
    @RequestMapping(value="grQueryShs.do")
    public @ResponseBody JsonResult grQueryShs() throws Exception {
    	return this.getSuccessJsonResult(yongHuDao.queryListByLx("1"), 0);
    }

    // 查询所有商户信息
    @RequestMapping(value="merchantList.do")
    public @ResponseBody Map<String, Object> queryMerchantList(Integer id, String sortType, 
    		Double longitude, Double latitude, String merchantType) throws Exception {
    	return yongHuService.getMerchantSimpleInfo(id, sortType, longitude, latitude, merchantType);
    }
    
    // 通过新规则生成的二维码获取客户的手机号
    @RequestMapping(value="getPhoneByQrcode.do")
	public @ResponseBody Map<String, Object> getPhoneByQrcode(String qrcode) throws Exception {
    	Map<String, Object> result = new HashMap<String, Object>();
    	if(qrcode.length()!=11) {
    		result.put("result", false);
    		result.put("failmsg", "二维码错误");
    		return result;
    	}
    	String s = "abcdefghij";
    	String yonghum = "";
    	for(int i=0;i<5;i++) {
    		yonghum += s.indexOf(qrcode.substring(i*2+1, i*2+2));
    	}
    	YongHu yh = yongHuDao.selectUserByYonghum(yonghum);
    	if(yh == null) {
    		result.put("result", false);
    		result.put("failmsg", "二维码错误");
    		return result;
    	}
		result.put("result", true);
		result.put("Phone", yh.getShoujih());
		return result;
	}
    
	@RequestMapping(value="valiPhone.do")
	public @ResponseBody Map<String, Object> valiPhone(String phone) {
		return yongHuService.valiPhone(phone);
	}
	
	@RequestMapping(value="valiPassword.do")
	public @ResponseBody Map<String, Object> valiPassword(String phone, String password) {
		return yongHuService.valiPassword(phone, password);
	}
	
	@RequestMapping(value="webLogin.do")
	public @ResponseBody Map<String, Object> webLogin(String phone, String password, String valicode, HttpSession session) {
		return yongHuService.webLogin(phone, password, valicode, session);
	}
}